import { Outlet, useNavigate } from 'react-router-dom'
import { apigetUserInfo } from './api'
import React, { useEffect } from 'react'
import Cookie from 'js-cookie'
import { connect } from 'react-redux'

const Layout = (props) => {

    const { dispatch } = props;

    const navigate = useNavigate()

    useEffect(() => {
        // 如果第二个参数为空数组的话 默认componentDidMount生命周期
        const token = Cookie.get('token')

        if (token) {
            apigetUserInfo().then(res => {
                // 请求成功 将用户信息保存到redux中
                dispatch({ type: 'CHANGE_USER_INFO', data: res.data })

                // 将权限信息保存到本地存储
                Cookie.set('auth', res.data.auth)


            }).catch(err => {
                // 跳转到登录页面
                navigate('/login')
            })
        }
    }, [])

    return <div className="layout-box">
        {/* 路由出口 */}
        <Outlet />
    </div>
}

const mapStateToProps = store => store

export default connect(mapStateToProps)(Layout)